<template>
  <div class="list_table" :style="'height:' + maxHeight + 'px'">
    <el-table
      :data="tableData"
      :cell-style="{ height: '40px !important', padding: '0px' }"
      stripe
      :max-height="maxHeight * 0.85"
      :height="maxHeight * 0.85"
      :cell-class-name="'cellClass'"
      @row-dblclick="rowClick.callback"
      @sort-change="sortChange"
    >
      <el-table-column v-if="useOrder && dataTable.length > 0" type="index" label="序号" width="80"></el-table-column>
      <template v-for="(item, index) in dataTable">
        <el-table-column
          :key="'table_' + index"
          :prop="item.prop"
          :label="item.name"
          :min-width="item.width"
          :sortable="item.sortable"
        >
          <template slot-scope="scope">
            <div v-if="!item.custom">
              <el-tooltip
                v-if="item.useTip && scope.row[item.prop].length > 16"
                effect="dark"
                :content="scope.row[item.prop]"
                placement="top"
              >
                <div class="cellClass">{{ scope.row[item.prop] }}</div>
              </el-tooltip>
              <div v-else class="cellClass">{{ scope.row[item.prop] }}</div>
            </div>
            <div v-else>
              <span v-show="item.custom === 'status'">{{ progressList[scope.row[item.prop] - 1] }}</span>
              <span v-show="item.custom === 'level'">{{ typeList[scope.row[item.prop] - 1] }}</span>
              <span v-show="item.custom === 'mode'">{{ scope.row[item.prop] === 1 ? '触发' : '周期' }}</span>
              <span v-show="item.custom === 'deviceType'">{{ typeObj[scope.row.topid] }}</span>
              <span v-if="item.custom === 'date'">{{ parseTime(scope.row[item.prop]) }}</span>
              <div v-show="item.custom === 'alarm'" class="column_state">
                <div class="dot" :style="`background-color: ${colorList[scope.row[item.prop] - 1]}`"></div>
                <span :style="`color: ${colorList[scope.row[item.prop] - 1]}`">{{
                  stateList[scope.row[item.prop] - 1]
                }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </template>
      <slot name="actionButton"></slot>
    </el-table>
    <!--jumper, total, size, ->-->
    <div class="page_foot">
      <el-pagination
        v-if="usePage"
        @size-change="changeSize"
        @current-change="switchPage"
        @prev-click="prevPage"
        @next-click="nextPage"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[15, 30, 50, 100]"
        :page-size="pageSize"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import axios from '@/utils/request';
const SERVICE_URL = process.env.VUE_APP_MAINTENANCE_API;
export default {
  props: {
    listUrl: {
      type: String,
      required: true
    },
    columnName: {
      type: Object,
      require: true
    },
    selectOption: {
      type: Boolean,
      default: () => false
    },
    maxHeight: {
      type: Number,
      default: () => 0
    },
    maxWidth: {
      type: Number,
      default: () => 0
    },
    useOrder: {
      type: Boolean,
      default: () => false
    },
    usePage: {
      type: Boolean,
      default: () => false
    },
    rowClick: {
      type: Object,
      default: () => {}
    },
    expanedParam: {
      type: Object,
      default: () => {
        '';
      }
    }
  },
  data() {
    return {
      dataTable: [],
      tableData: [],
      sourceData: [],
      colorList: ['#F56C6C', '#67C23A'],
      pageSize: 15,
      typeList: ['一级', '二级', '三级', '四级', '五级'],
      stateList: ['报警', '恢复'],
      progressList: ['待确认', '待处理', '处理中', '延时处理', '处理完成', '已恢复', '已忽略'],
      total: 0,
      typeObj: {
        1: '搬运类',
        2: '输送类',
        3: '包装类',
        4: '其他类'
      },
      page: 1
    };
  },
  mounted() {
    this.getListData();
  },
  methods: {
    changeStyle() {
      const selectEl = document.querySelector('.el-table__fixed-right');
      if (this.tableData.length === 1) {
        if (selectEl) selectEl.style.height = 'calc(100% - 92px)';
      }
    },
    // 行高样式
    rowStyle(style) {
      console.log('style', style);
    },
    // 转化时间
    parseTime(date) {
      let time = date || '';
      const year = time.match(/^\d{4}-\d{1,2}-\d{1,2}/g);
      const second = time.match(/\d{1,2}:\d{1,2}:\d{1,2}/g);
      return year + ' ' + second;
    },
    // 初始化
    initData(listData) {
      let temp = listData[0];
      let includeKeys = Object.keys(this.columnName);
      let tempArr = [includeKeys.length];
      const keys = Object.keys(temp);
      keys.forEach((key, index) => {
        let tempIndex = includeKeys.indexOf(key);
        let value = temp[key];
        if (tempIndex > -1) {
          let width = Math.round(this.maxWidth / includeKeys.length) + 40;
          let columnVal = this.columnName[key];
          let obj = {
            prop: key,
            custom: false,
            width: width.toString()
          };
          if (typeof columnVal === 'object') {
            obj.name = columnVal.name;
            obj.custom = columnVal.type || '';
            obj.useTip = columnVal.useTip || false;
            if (columnVal.sortable) obj.sortable = columnVal.sortable;
            if (columnVal.width) obj.width = columnVal.width;
          } else {
            obj.name = columnVal;
            obj.sortable = false;
          }
          tempArr[tempIndex] = obj;
        }
      });
      console.log(tempArr);
      return tempArr;
    },
    // 获取列表数据
    getListData() {
      let param = Object.assign({ page: this.page, page_size: this.pageSize }, this.expanedParam);
      axios
        .request({
          method: 'GET',
          url: SERVICE_URL + '/' + this.listUrl,
          params: param,
          headers: {
            'Content-Type': 'application/json',
            hideLoading: true
          }
        })
        .then(res => {
          const data = res.data;
          if (data) {
            this.tableData = data.list !== undefined ? (data.list ? data.list : []) : data;
            this.sourceData = data.list !== undefined ? (data.list ? data.list : []) : data;
            this.total = data.list !== undefined ? res.data.total : data.length;
          } else {
            this.total = 0;
            this.tableData = [];
          }
          if (this.tableData && this.tableData.length > 0) {
            this.dataTable = this.initData(this.tableData);
            this.changeStyle();
          } else {
            const keys = Object.keys(this.columnName);
            let temp = [];
            keys.forEach(key => {
              const keyVal = this.columnName[key];
              if (typeof keyVal === 'object') {
                temp.push({
                  name: keyVal.name,
                  prop: key
                });
              } else {
                temp.push({
                  name: keyVal,
                  prop: key
                });
              }
            });
            this.dataTable = temp;
          }
          if (this.selectOption) {
            this.$emit('initOption', this.tableData);
          }
        });
    },
    // 排序
    sortChange(column) {
      const order = column.order;
      this.expanedParam.sortType = order.startsWith('a') ? 'asc' : 'desc';
      this.expanedParam.sort = column.prop;
      this.getListData();
    },
    // 改编页码
    changeSize(row) {
      this.pageSize = row;
      this.getListData();
    },
    // 上一页
    prevPage() {
      this.page--;
      this.getListData();
    },
    // 下一页
    nextPage() {
      this.page++;
      this.getListData();
    },
    // 跳页
    switchPage(row) {
      this.page = row;
      this.getListData();
    }
  }
};
</script>
<style lang="scss" scoped>
.cellClass {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.table_img {
  width: 40px;
  height: 30px;
}
.el-table::before {
  height: 0 !important;
}
.list_table {
  position: relative;
  .page_foot {
    position: absolute;
    bottom: 20px;
    right: 0px;
  }
}
::v-deep {
  .el-table__fixed-body-wrapper {
    top: 55px !important;
  }
}
</style>
